package org.opens.init;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;
import java.nio.charset.Charset;

/**
 * 功能描述
 *
 * @author: zhangyuming
 * @date: 2023/9/9 11:54
 */
@Configuration
@Slf4j
public class DbinitConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public DataSourceInitializer dataSourceInitializer(){
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        dataSourceInitializer.setDatabasePopulator(databasePopulator());
        dataSourceInitializer.setEnabled(true);

        log.info("数据库脚本已自动执行.");

        return dataSourceInitializer;
    }

    private DatabasePopulator databasePopulator(){
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(new ClassPathResource("sql/dbinit-demo.sql"));
        //populator.addScript(sqlScriptData);

        // 设置脚本编码
        populator.setSqlScriptEncoding("UTF-8");
        return populator;
    }

}
